﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace CommHelper
{
    /// <summary>
    /// 配置文件帮助类
    /// </summary>
    public class AppSettingsHelper
    {
        /// <summary>
        /// 通过节点名，获取节点值
        /// </summary>
        /// <param name="appname"></param>
        /// <returns></returns>
        public static string GetText(string appname)
        {
            string text = string.Empty;
            if (System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains(appname))
            {
                text = System.Configuration.ConfigurationManager.AppSettings[appname];
            }
            return text;
        }

        /// <summary>
        ///  通过节点名，获取节点值,并作整数显示
        /// </summary>
        /// <param name="appname"></param>
        /// <returns></returns>
        public static int GetInt(string appname)
        {
            int intvalue = 0;
            if (System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains(appname))
            {
                Int32.TryParse(System.Configuration.ConfigurationManager.AppSettings[appname], out intvalue);
            }
            return intvalue;
        }

        /// <summary>
        /// 设置节点的值
        /// </summary>
        /// <param name="appname">节点名称</param>
        /// <param name="value">节点值</param>
        public static void SetAppSettingsValue(string appname, string value)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
            System.Xml.XmlNode node = doc.SelectSingleNode(@"//add[@key='" + appname + "']");
            System.Xml.XmlElement ele = (System.Xml.XmlElement)node;
            ele.SetAttribute("value", value);
            doc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
